//
//  TYZPickerTool.m
//  ESTSCRMAPP
//
//  Created by 李贤立 on 2018/10/12.
//  Copyright © 2018年 Capfer. All rights reserved.
//

#import "TYZPickerTool.h"
#define TYZPickerTool_Year      [@"年" S]
#define TYZPickerTool_Month     [@"月" S]
#define TYZPickerTool_Hour      [@"时" S]
#define TYZPickerTool_Minute    [@"分" S]
#define TYZPickerTool_DateTitle [@"选择日期" S]
#define TYZPickerTool_TimeTitle [@"选择时间" S]
@interface TYZPickerTool () <UIPickerViewDelegate, UIPickerViewDataSource>
/**
 *  是否是二维选择
 */
@property(nonatomic, assign) BOOL twoDimensional;
/**
 *  选择器父控件
 */
@property(nonatomic, strong) UIView *pickerView;
/**
 *  覆盖按钮
 */
@property(nonatomic, strong) UIButton *couverWindowButton;
/**
 *  选择了第几个
 */
@property(nonatomic, strong) NSArray<NSNumber *> *selectedNumber;
/**
 *  第一列数据
 */
@property(nonatomic, strong) NSArray<NSString *> *firstStrings;
/**
 *  第二列数据
 */
@property(nonatomic, strong) NSArray<NSString *> *secondStrings;
/**
 *  选择了第一列的第几个
 */
@property(nonatomic, assign) NSInteger section;
/**
 *  选择了第二列的第几个
 */
@property(nonatomic, assign) NSInteger row;
/**
 *  选择器
 */
@property(nonatomic, strong) UIPickerView *picker;
/**
 *  选择器标题
 */
@property(nonatomic, strong) UILabel *titleLabel;
#pragma mark - 日期选择器内容
/**
 *  年份数据源
 */
@property(nonatomic, strong) NSArray<NSString *> *yearData;
/**
 *  月份数据源
 */
@property(nonatomic, strong) NSArray<NSString *> *monthData;
/**
 *  年月的数据源
 */
@property(nonatomic, strong) NSArray<NSArray *> *yearMonthData;
/**
 *  小时数据源
 */
@property(nonatomic, strong) NSArray<NSString *> *hourData;
/**
 *  分钟数据源
 */
@property(nonatomic, strong) NSArray<NSString *> *minuteData;
/**
 *  时分的数据源
 */
@property(nonatomic, strong) NSArray<NSArray *> *hourMinuteData;
/**
 *  时间选择器
 */
@property(nonatomic, strong) UIDatePicker *datePicker;
/**
 *  选择器类型
 */
@property(nonatomic, assign) TYZDatePickerMode datePickerMode;
/**
 *  选择了的时间
 */
@property(nonatomic, copy) NSString *dateString;
/**
 *  选择了的时间的回调
 */
@property(nonatomic) void(^didSelectedDateBlock)(NSString *dateString);
@end

@implementation TYZPickerTool
- (instancetype)init {
    if (self = [super init]) {
        [self setupUI];
        [self addNormalPicker];
        self.datePickerMode = DatePickerMode_Default;
    }
    return self;
}
- (instancetype)initWithDateMode {
    if (self = [super init]) {
        [self setupUI];
        [self addDatePicker];
    }
    return self;
}
/**
 调出选择器
 
 @param pickerTitle 选择器标题
 @param dataArray 数据源
 @param selectedValue 默认选择的值
 */
- (instancetype)initWithTitle:(NSString *)pickerTitle dataArray:(NSArray *)dataArray selectedValue:(NSArray *)selectedValue {
    if (self = [self init]) {
        self.pickerTitle = pickerTitle;
        self.selectedValue = selectedValue;
        self.dataArray = dataArray;
    }
    return self;
}
/**
 调出选择器
 
 @param pickerTitle 选择器标题
 @param dataArray 数据源
 @param selectedValue 默认选择的值
 @param complement 完成回调
 */
+ (void)showPickerWithTitle:(NSString *)pickerTitle dataArray:(NSArray *)dataArray selectedValue:(NSArray *)selectedValue complement:(void(^)(NSArray<NSNumber *> *numberArray))complement {
    TYZPickerTool *tool = [[TYZPickerTool alloc] init];
    tool.pickerTitle = pickerTitle;
    tool.selectedValue = selectedValue;
    tool.dataArray = dataArray;
    tool.didChooseNumberBlock = complement;
}
/**
 调出日期和时间选择器
 
 @param dateString 默认时间
 @param datePickerMode 选择器的类型
 @param complement 完成回调
 */
+ (void)showDatePickerWithDateString:(NSString *)dateString datePickerMode:(TYZDatePickerMode)datePickerMode complement:(void(^)(NSString *dateString))complement {
    [self showDatePickerWithTitle:nil dateString:dateString datePickerMode:datePickerMode complement:complement];
}
/**
 调出日期和时间选择器

 @param pickerTitle 选择器标题
 @param dateString 默认时间
 @param datePickerMode 选择器的类型
 @param complement 完成回调
 */
+ (void)showDatePickerWithTitle:(NSString *)pickerTitle dateString:(NSString *)dateString datePickerMode:(TYZDatePickerMode)datePickerMode complement:(void(^)(NSString *dateString))complement {
    if (datePickerMode == DatePickerMode_Date || datePickerMode == DatePickerMode_Time || datePickerMode == DatePickerMode_DateTime) {
        TYZPickerTool *tool = [[TYZPickerTool alloc] initWithDateMode];
        tool.dateString = dateString;
        tool.pickerTitle = pickerTitle;
        tool.datePickerMode = datePickerMode;
        tool.didSelectedDateBlock = complement;
        [tool creatDateTimePickerWithDateString:dateString datePickerMode:datePickerMode];
    } else {
        TYZPickerTool *tool = [[TYZPickerTool alloc] init];
        NSString *title;
        NSArray *dataArray;
        NSArray *selectedValue;
        switch (datePickerMode) {
            case DatePickerMode_YearMonth: {
                title = TYZPickerTool_DateTitle;
                dataArray = tool.yearMonthData;
                NSArray *arr = [dateString componentsSeparatedByString:@"-"];
                if (arr.count == 2) {
                    selectedValue = @[[NSString stringWithFormat:@"%@%@", arr.firstObject, TYZPickerTool_Year], [NSString stringWithFormat:@"%@%@", arr.lastObject, TYZPickerTool_Month]];
                }
            }
                break;
            case DatePickerMode_Year: {
                title = TYZPickerTool_DateTitle;
                dataArray = tool.yearData;
                if ([dateString containsString:TYZPickerTool_Year]) {
                    selectedValue = @[dateString];
                }
            }
                break;
            case DatePickerMode_Month: {
                title = TYZPickerTool_DateTitle;
                dataArray = tool.monthData;
                if ([dateString containsString:TYZPickerTool_Month]) {
                    selectedValue = @[dateString];
                }
            }
                break;
            case DatePickerMode_HourMinute: {
                title = TYZPickerTool_TimeTitle;
                dataArray = tool.hourMinuteData;
                NSArray *arr = [dateString componentsSeparatedByString:@":"];
                if (arr.count == 2) {
                    selectedValue = @[[NSString stringWithFormat:@"%@%@", arr.firstObject, TYZPickerTool_Hour], [NSString stringWithFormat:@"%@%@", arr.lastObject, TYZPickerTool_Minute]];
                }
            }
                break;
            case DatePickerMode_Hour: {
                title = TYZPickerTool_TimeTitle;
                dataArray = tool.hourData;
                if ([dateString containsString:TYZPickerTool_Hour]) {
                    selectedValue = @[dateString];
                }
            }
                break;
            case DatePickerMode_Minute: {
                title = TYZPickerTool_TimeTitle;
                dataArray = tool.minuteData;
                if ([dateString containsString:TYZPickerTool_Minute]) {
                    selectedValue = @[dateString];
                }
            }
                break;
            default:
                break;
        }
        tool.pickerTitle = pickerTitle ? pickerTitle : title;
        tool.selectedValue = selectedValue;
        tool.dataArray = dataArray;
        tool.dateString = dateString;
        tool.datePickerMode = datePickerMode;
        tool.didSelectedDateBlock = complement;
    }
}

- (void)creatDateTimePickerWithDateString:(NSString *)dateString datePickerMode:(TYZDatePickerMode)datePickerMode {
    if (!dateString) return;
    switch (datePickerMode) {
        case DatePickerMode_Date:
            if (self.pickerTitle == nil) {
                self.pickerTitle = TYZPickerTool_DateTitle;
            }
            _datePicker.date = [NSDate dateForYYYYMMDD:dateString];
            _datePicker.datePickerMode = UIDatePickerModeDate;
            break;
        case DatePickerMode_Time:
            if (self.pickerTitle == nil) {
                self.pickerTitle = TYZPickerTool_TimeTitle;
            }
            _datePicker.date = [NSDate dateForHHMMSS:dateString];
            _datePicker.datePickerMode = UIDatePickerModeTime;
            break;
        case DatePickerMode_DateTime:
            if (self.pickerTitle == nil) {
                self.pickerTitle = TYZPickerTool_TimeTitle;
            }
            _datePicker.date = [NSDate dateForYYYYMMDDHHMMSS:dateString];
            _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
            break;
        default:
            break;
    }
}
#pragma mark - 设置UI
- (void)setupUI {
    UIWindow *window = [TYZApplication sharedApplication].keyWindow;
    [window addSubview:self];
    self.frame = window.bounds;
    self.couverWindowButton = [TYZButton buttonWithType:UIButtonTypeCustom];
    [window addSubview:self.couverWindowButton];
    [self.couverWindowButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(window);
    }];
    [self.couverWindowButton setBackgroundColor:[UIColor blackColor]];
    [self.couverWindowButton setAlpha:0.5];
    [self.couverWindowButton addTarget:self action:@selector(didClickCoverWindowButton) forControlEvents:UIControlEventTouchUpInside];
    [window addSubview:self.pickerView];
    [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(window);
        make.height.mas_equalTo(TYZPickerTool_Height);
    }];
    [self setupPickerView];
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_PickerToolDidShow object:nil];
}
- (void)setupPickerView {
    [self.pickerView.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    UIView *tip = [[UIView alloc] init];
    [self.pickerView addSubview:tip];
    [tip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.pickerView);
        make.height.mas_equalTo(40);
    }];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tip addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tip);
        make.left.equalTo(tip).offset(20);
    }];
    [leftButton setTitle:[@"取消" S] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(didClickCoverWindowButton) forControlEvents:UIControlEventTouchUpInside];
    [leftButton setTitleColor:TYZBlackColor forState:UIControlStateNormal];
    leftButton.titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = self.pickerTitle;
    [tip addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(tip);
    }];
    titleLabel.textColor = TYZBlackColor;
    titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    self.titleLabel = titleLabel;
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [tip addSubview:rightButton];
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(tip);
        make.right.equalTo(tip).offset(-20);
    }];
    [rightButton setTitle:[@"确定" S] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(didClickSureButton) forControlEvents:UIControlEventTouchUpInside];
    [rightButton setTitleColor:TYZBlackColor forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:CoreInfo.fontSize];
    [tip addLine];
}
- (void)addNormalPicker {
    [self.pickerView addSubview:self.picker];
    [self.picker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.pickerView);
        make.height.mas_equalTo(216);
    }];
}
- (void)addDatePicker {
    [self.pickerView addSubview:self.datePicker];
    [self.datePicker mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.pickerView);
        make.height.mas_equalTo(216);
    }];
}
#pragma mark - actions
// 点击了取消
- (void)didClickCoverWindowButton {
    [self removeFromSuperview];
    [self.couverWindowButton removeFromSuperview];
    [self.pickerView removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_PickerToolDidHidden object:nil];
}
// 点击了确定
- (void)didClickSureButton {
    [self didClickCoverWindowButton];
    NSArray *arr = self.selectedNumber;
    if (self.datePickerMode == DatePickerMode_Default) {
        if (arr == nil) {
            arr = @[@(self.section), @(self.row)];
        }
        if (self.dataArray.count > 0) {
            if (self.didChooseNumberBlock) {
                self.didChooseNumberBlock(arr);
            }
        }
    } else {
        if (self.didSelectedDateBlock) {
            self.didSelectedDateBlock(self.dateString);
        }
    }
}
// 选择了日期/时间
- (void)didSelectedDatePicker:(UIDatePicker *)datePicker {
    NSString *formatter = @"";
    switch (self.datePickerMode) {
        case DatePickerMode_Date:
            formatter = @"yyyy-MM-dd";
            break;
        case DatePickerMode_Time:
            formatter = @"hh-mm-ss";
            break;
        case DatePickerMode_DateTime:
            formatter = @"yyyy-MM-dd HH:mm:ss";
            break;
        default:
            break;
    }
    self.dateString = [datePicker.date formatterDate:formatter];
}
// 设置默认选择项
- (void)setSelectedData {
    if (self.selectedValue && self.dataArray) {
        [self.picker reloadAllComponents];
        if (self.twoDimensional) {
            // 默认选择项
            __block NSInteger section = 0;
            __block NSInteger row = 0;
            [self.dataArray enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj1, NSUInteger idx1, BOOL * _Nonnull stop) {
                if ([obj1.firstObject isEqualToString:self.selectedValue.firstObject]) {
                    section = idx1;
                    [obj1.lastObject enumerateObjectsUsingBlock:^(id  _Nonnull obj2, NSUInteger idx2, BOOL * _Nonnull stop) {
                        if ([obj2 isEqualToString:self.selectedValue.lastObject]) {
                            row = idx2;
                            *stop = YES;
                        }
                    }];
                }
            }];
            self.section = section;
            self.row = row;
        } else {
            // 默认选择项
            __block NSInteger row = 0;
            [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([self.selectedValue.firstObject isEqualToString:obj]) {
                    row = idx;
                    *stop = YES;
                }
            }];
            self.row = row;
            [self.picker selectRow:row inComponent:0 animated:NO];
        }
    }
}
#pragma mark - setter & getter
- (void)setDataArray:(NSArray *)dataArray {
    _dataArray = dataArray;
    if (dataArray.count > 0) {
        self.twoDimensional = [dataArray.firstObject isKindOfClass:[NSArray class]];
    } else {
        [self.picker removeFromSuperview];
        [self.pickerView noDataWithMessage:[@"没有数据" S] click:nil];
    }
}
- (void)setPickerTitle:(NSString *)pickerTitle {
    _pickerTitle = pickerTitle;
    self.titleLabel.text = pickerTitle;
}
- (void)setTwoDimensional:(BOOL)twoDimensional {
    _twoDimensional = twoDimensional;
    if (twoDimensional) {
        __block NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.dataArray.count];
        [self.dataArray enumerateObjectsUsingBlock:^(NSArray * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [arrM addObject:obj.firstObject];
        }];
        self.firstStrings = [arrM mutableCopy];
        NSArray *arr = (NSArray *)self.dataArray.firstObject;
        // 默认第一列的数据
        self.secondStrings = arr.lastObject;
    }
    [self setSelectedData];
}
- (void)setSelectedValue:(NSArray<NSString *> *)selectedValue {
    _selectedValue = selectedValue;
    [self setSelectedData];
}
- (void)setSection:(NSInteger)section {
    _section = section;
    NSArray *arr = (NSArray *)self.dataArray[section];
    self.secondStrings = arr.lastObject;
    [self.picker selectRow:section inComponent:0 animated:NO];
    self.row = 0;
}
- (void)setRow:(NSInteger)row {
    _row = row;
    if (self.twoDimensional) {
        [self.picker reloadComponent:1];
        [self.picker selectRow:row inComponent:1 animated:NO];
    }
}
#pragma mark - UIPickerViewDelegate, UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    if (self.twoDimensional) {
        return 2;
    } else {
        return 1;
    }
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (self.twoDimensional) {
        if (component == 0) {
            return self.firstStrings.count;
        } else {
            return self.secondStrings.count;
        }
    } else {
        return self.dataArray.count;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (self.twoDimensional) {
        if (component == 0) {
            return self.firstStrings[row];
        } else {
            return self.secondStrings[row];
        }
    } else {
        return self.dataArray[row];
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    switch (self.datePickerMode) {
        case DatePickerMode_Default:
            if (self.twoDimensional) {
                if (component == 0) {
                    self.section = row;
                } else {
                    self.row = row;
                }
                self.selectedNumber = @[@(self.section), @(self.row)];
            } else {
                self.selectedNumber = @[@(0), @(row)];
            }
            break;
        case DatePickerMode_Year:
            self.dateString = self.yearData[row];
            break;
        case DatePickerMode_Month:
            self.dateString = self.monthData[row];
            break;
        case DatePickerMode_YearMonth:
            self.dateString = [NSString stringWithFormat:@"%@-%@", [self.yearData[self.section] componentsSeparatedByString:TYZPickerTool_Year].firstObject, [self.monthData[self.row] componentsSeparatedByString:TYZPickerTool_Month].firstObject];
            break;
        case DatePickerMode_Hour:
            self.dateString = self.hourData[row];
            break;
        case DatePickerMode_Minute:
            self.dateString = self.minuteData[row];
            break;
        case DatePickerMode_HourMinute:
            self.dateString = [NSString stringWithFormat:@"%@-%@", [self.hourData[self.section] componentsSeparatedByString:TYZPickerTool_Hour].firstObject, [self.minuteData[self.row] componentsSeparatedByString:TYZPickerTool_Minute].firstObject];
            break;
        default:
            break;
    }
}
#pragma mark - setter & getter
- (UIView *)pickerView {
    if (_pickerView == nil) {
        _pickerView = [[UIView alloc] init];
        _pickerView.backgroundColor = TYZWhiteColor;
    }
    return _pickerView;
}
- (UIPickerView *)picker {
    if (_picker == nil) {
        _picker = [[UIPickerView alloc] init];
        _picker.delegate = self;
        _picker.dataSource = self;
    }
    return _picker;
}
- (UIDatePicker *)datePicker {
    if (_datePicker == nil) {
        _datePicker = [[UIDatePicker alloc] init];
        // 设置日期选择控件的地区
        _datePicker.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"zh_Hans_CN"];
        // 设置DatePicker的时区。
        _datePicker.timeZone = [NSTimeZone defaultTimeZone];
        [_datePicker addTarget:self action:@selector(didSelectedDatePicker:) forControlEvents:UIControlEventValueChanged];
    }
    return _datePicker;
}
#pragma mark - 时间选择器数据源
- (NSArray<NSString *> *)yearData {
    if (_yearData == nil) {
        NSInteger count = TYZDatePicker_EndYear - TYZDatePicker_StartYear;
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:count];
        for (NSInteger i = 0; i < count; i++) {
            [arrM addObject:[NSString stringWithFormat:@"%ld%@", TYZDatePicker_StartYear + i, TYZPickerTool_Year]];
        }
        _yearData = [arrM mutableCopy];
    }
    return _yearData;
}
- (NSArray<NSString *> *)monthData {
    if (_monthData == nil) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:12];
        for (NSInteger i = 0; i < 12; i++) {
            [arrM addObject:[NSString stringWithFormat:@"%ld%@", i + 1, TYZPickerTool_Month]];
        }
        _monthData = [arrM mutableCopy];
    }
    return _monthData;
}
- (NSArray<NSString *> *)hourData {
    if (_hourData == nil) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:24];
        for (NSInteger i = 0; i < 24; i++) {
            [arrM addObject:[NSString stringWithFormat:@"%ld%@", (long)i, TYZPickerTool_Hour]];
        }
        _hourData = [arrM mutableCopy];
    }
    return _hourData;
}
- (NSArray<NSString *> *)minuteData {
    if (_minuteData == nil) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:60];
        for (NSInteger i = 0; i < 60; i++) {
            [arrM addObject:[NSString stringWithFormat:@"%ld%@", (long)i, TYZPickerTool_Minute]];
        }
        _minuteData = [arrM mutableCopy];
    }
    return _minuteData;
}
- (NSArray<NSArray *> *)yearMonthData {
    if (_yearMonthData == nil) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.yearData.count];
        for (NSString *year in self.yearData) {
            [arrM addObject:@[year, self.monthData]];
        }
        _yearMonthData = [arrM mutableCopy];
    }
    return _yearMonthData;
}
- (NSArray<NSArray *> *)hourMinuteData {
    if (_hourMinuteData == nil) {
        NSMutableArray *arrM = [NSMutableArray arrayWithCapacity:self.hourData.count];
        for (NSString *hour in self.hourData) {
            [arrM addObject:@[hour, self.minuteData]];
        }
        _hourMinuteData = [arrM mutableCopy];
    }
    return _hourMinuteData;
}
@end
